package dian.qing.li.demo.security.config.security;

import dian.qing.li.demo.security.constants.Constants;
import dian.qing.li.demo.security.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TOKEN拦截器
 *
 * @author: liqingdian
 **/
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final AntPathRequestMatcher LOGIN_MATCHER = new AntPathRequestMatcher("/login", "POST");

    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (LOGIN_MATCHER.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = JwtUtils.getJwtToken(request);
        if (StringUtils.isNotBlank(token)) {
            String username = JwtUtils.username(token, Constants.JWT_SECRET);
            if (StringUtils.isNotBlank(username)) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (JwtUtils.verifyToken(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
